package com.woniu.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.dto.PageData;
import com.woniu.entity.Customer;
import com.woniu.entity.InsuranceTeam;
import com.woniu.exception.IDDuplicateException;
import com.woniu.service.InsuranceTeamService;
import com.woniu.mapper.InsuranceTeamMapper;
import com.woniu.utils.ResData;
import com.woniu.utils.ResEnum;
import com.woniu.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;

/**
* @author Administrator
* @description 针对表【insurance_team】的数据库操作Service实现
* @createDate 2024-04-10 15:48:53
*/
@Service
public class InsuranceTeamServiceImpl extends ServiceImpl<InsuranceTeamMapper, InsuranceTeam>
    implements InsuranceTeamService{

    @Autowired
    private InsuranceTeamMapper insuranceTeamMapper;
    @Override
    public PageInfo<InsuranceTeam> queryGroupList(PageData<InsuranceTeam> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<InsuranceTeam> insuranceTeams = insuranceTeamMapper.queryGroupList(pageData.getParams());
        return new PageInfo<>(insuranceTeams);
    }

    @Override
    public int addGroup(InsuranceTeam insuranceTeam) {
        String id = insuranceTeam.getId();
        boolean isDuplicate = isIdDuplicate(id);
        if (isDuplicate) {
            throw new IDDuplicateException();
        }else if (id==null){
            insuranceTeam.setId(generateID());
            insuranceTeamMapper.addGroup(insuranceTeam);
            return ResData.success("ID已经生成").getCode();
        }

        // 如果 id 不重复，则执行插入操作
        return insuranceTeamMapper.addGroup(insuranceTeam);
    }

    /**
     * 删除小组
     * @param
     * @return
     */
    @Override
    public int deleteGroup(String id) {
        return insuranceTeamMapper.deleteGroup(id);
    }

    /**
     * 判断id是否重复
     * @param id
     * @return
     */
    private boolean isIdDuplicate(String id) {
        InsuranceTeam existingTeam = insuranceTeamMapper.findById(id);
        return existingTeam != null;
    }
    private static long counter = 0;
    public  String generateID() {
        long timestamp = Instant.now().toEpochMilli();
        return "ID-" + timestamp + "-" + counter++;
    }

}




